package pku;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

public class WriteObjectThread extends Thread {

	private HashMap<String, String> tempCount = null;
	private HashMap<String, ArrayList<ByteMessage>> tempMsgs =null;
	private Long paraentThreadId = 0l;
	private String typeFlag = "1";
	
	public WriteObjectThread(HashMap<String, String> t,HashMap<String, ArrayList<ByteMessage>> mf,Long ptid,String tf){
		this.tempCount = t;
		this.tempMsgs = mf;
		this.paraentThreadId = ptid;
		this.typeFlag = tf;
	}
	
	@Override
	public void run() {
		File file = null;
		ObjectOutputStream objOut = null;
		HashMap<String, ArrayList<ByteMessage>> msgsfinal =null;
		FileOutputStream fos = null;
		BufferedOutputStream bos =  null;
		try {
			for (String topic : this.tempMsgs.keySet()) {
				msgsfinal = new HashMap<String, ArrayList<ByteMessage>>();
				msgsfinal.put(topic, tempMsgs.get(topic));
				file = new File(MessageStore.filePath + this.tempCount.get(topic)+ ".hb");
				fos = new FileOutputStream(file);
				bos =  new BufferedOutputStream(fos);
				objOut = new ObjectOutputStream(bos);
				objOut.writeObject(msgsfinal);
				objOut.flush();
			}
			if("0".equals(this.typeFlag)){
				file = new File(MessageStore.filePath + "topicindex.hb");
				fos = new FileOutputStream(file);
				bos =  new BufferedOutputStream(fos);
				objOut = new ObjectOutputStream(bos);
				objOut.writeObject(MessageStore.store.topicCount);
				objOut.flush();
				objOut.close();
			}
			MessageStore.store.threadMap.get(this.paraentThreadId).remove(Thread.currentThread().getId());
		} catch (Exception e) {
			 e.printStackTrace();
		}finally {
			try {
				if(null != objOut){
					objOut.close();
				}
				if(null != bos){
					bos.close();
				}
				if(null != fos){
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}
